/**
 * 
 */
package org.conan.groupapp.framework.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.NumberUtils;
import org.conan.groupapp.framework.dao.IBaseDao;
import org.conan.groupapp.framework.entity.PageData;
import org.conan.groupapp.framework.entity.ParamBean;
import org.conan.groupapp.framework.service.IBaseService;

/**
 * @author Administrator
 *
 */
public abstract class BaseServiceImpl<T extends ParamBean> implements IBaseService<T> {
	
	protected IBaseDao<T> iBaseDao;


	@Override
	public T save(T t) throws Exception {
		String result = iBaseDao.insert(t);
		t.setPrimaryKey(null);
		if(NumberUtils.isDigits(result)){
			t.setPrimaryKey(Integer.valueOf(result));			
		}
		return t;
	}

	@Override
	public T modify(T t) throws Exception {
		t.setAffectedRows(iBaseDao.updateByPrimaryKey(t));
		return t;
	}

	@Override
	public int remove(Integer pirmaryKey) throws Exception {
		return iBaseDao.deleteByPrimaryKey(pirmaryKey);
	}
	
	@Override
	public T removeByCondition(T t) throws Exception {
		t.setAffectedRows(iBaseDao.deleteByCondition(t));
		return t;
	}

	@Override
	public List<T> selectByCondition(T t, int rowStart, int rowEnd)
			throws Exception {
		return iBaseDao.selectByCondition(t,rowStart,rowEnd);
	}
	
	@Override
	public List<Map> selectMapByCondition(T t, int rowStart, int rowEnd)
			throws Exception {
		return iBaseDao.selectMapByCondition(t,rowStart,rowEnd);
	}

	@Override
	public int countByCondition(T t) throws Exception {
		return iBaseDao.countByCondition(t);
	}
	
	@Override
	public T selectByPrimaryKey(Integer pirmaryKey) throws Exception {
		return iBaseDao.selectByPrimaryKey(pirmaryKey);
	}
	
	
	@Override
	public PageData pageList(T t) throws Exception {
		PageData pd = new PageData();
		int totalRecords = this.countByCondition(t);
		List<T> list = new ArrayList<T>();
		int currentPage = t.getPage();
		int pageSize = t.getRows();
		pd.cal(pageSize, totalRecords, currentPage);
		if(totalRecords>0){
			list = selectByCondition(t, pd.getStartIndex(), pd.getEndIndex());
		}
		pd.setRows(list);
		return pd;
	} 
	
	@Override
	public PageData pageMapList(T t) throws Exception {
		PageData pd = new PageData();
		int totalRecords = this.countByCondition(t);
		List<Map> list = new ArrayList<Map>();
		int currentPage = t.getPage();
		int pageSize = t.getRows();
		pd.cal(pageSize, totalRecords, currentPage);
		if(totalRecords>0){
			list = selectMapByCondition(t, pd.getStartIndex(), pd.getEndIndex());
		}
		pd.setRows(list);
		return pd;
	} 
	
	@Override
	public PageData convertPageList(PageData pd){
		return pd;
	}
	
	@Override
	public String toPageJson(PageData pd) {
		return null;
	}

	public IBaseDao<T> getiBaseDao() {
		return iBaseDao;
	}

	public void setiBaseDao(IBaseDao<T> iBaseDao) {
		this.iBaseDao = iBaseDao;
	}

}
